﻿using System;
using System.IO;
using CacheService.Standard;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;
using WebApi.Filter;
using Wx.Standard;
using Wx.Standard.IService;
using Wx.Standard.Options;

namespace WebApi
{
    public class Startup
    {
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            this.Configuration = builder.Build();
            //Configuration = builder.Build();
        }
        /// <summary>
        /// Gets the configuration.
        /// </summary>
        /// <value>The configuration.</value>
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.AddMemoryCache();
            //缓存配置
            var cacheStr = Configuration.GetConnectionString("cache");
            if (string.IsNullOrWhiteSpace(cacheStr))
            {
                services.AddSingleton<ICache, MemoryForCache>();
            }
            else
            {
                services.AddSingleton(typeof(ICache), new RedisForCache(new RedisCacheOptions
                {
                    Configuration = cacheStr,
                    InstanceName = "WxApp"
                }, 0));
            }
            //跨域设置
            services.AddCors();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            });
            services.AddMvc(c => { c.Filters.Add(typeof(Filter.LoginFilterAttribute)); })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //所有接口注入
            //services.AutoFacInterface();
            //微信API配置
            //services.UseWeChatApi(Configuration.GetSection("WeChat"));
            //微信支付配置
            //services.UseWeChatPay(Configuration.GetSection("Pay"));
            //小程序配置
            services.UseWeChatApp(Configuration.GetSection("SmallApp"));

            //services.BuildServiceProvider();


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            /*
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });*/
            //添加NLog  
            loggerFactory.AddNLog();
            env.ConfigureNLog("nlog.config");
            #region 解决Ubuntu Nginx 代理不能获取IP问题
            app.UseForwardedHeaders(new ForwardedHeadersOptions
                {ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto});
            #endregion
            //自定义异常处理
            app.UseMiddleware<ExceptionFilter>();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseCors("AllowAll");
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            //app.UseMvcWithDefaultRoute();

        }
    }
}
